package com.wad.manager.service.impl;

import cn.hutool.core.date.DateUtil;
import com.wad.common.exception.BussinessException;
import com.wad.manager.properties.MinioProperties;
import com.wad.manager.service.FileUploadService;
import com.wad.vo.common.ResultCodeEnum;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author wad
 * @date 2023/12/03 14:43
 * @project e-commerce
 **/
@Service
public class FileUploadServiceImpl implements FileUploadService {


    @Resource
    private MinioProperties minioProperties;
    @Override
    public String upload(MultipartFile file) {
        try {
            MinioClient minioClient= MinioClient.builder().
                    endpoint(minioProperties.getEndpointUrl()).
                    credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey()).build();
            //创建bucket
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!bucketExists){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }


            //获取上传的文件名称,
            // 每个上传的文件都是唯一的 uuid生成+文件名
            // 根据当前日期对上传的文件进行分组 20231203
            String dataDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String filename = dataDir+"/"+uuid+file.getOriginalFilename();
            //得到文件的输入流
            InputStream inputStream = file.getInputStream();
            //文件上传
            minioClient.putObject(PutObjectArgs.builder().
                    bucket(minioProperties.getBucketName()).
                    object(filename).
                    stream(inputStream, file.getSize(), -1).
                    build());
            //获取上传文件在minio中的路径 //todo文件名可能会重复，这里需要进行唯一性设置
            String url=minioProperties.getEndpointUrl()+"/"+minioProperties.getBucketName()+"/"+filename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            throw new BussinessException(ResultCodeEnum.SYSTEM_ERROR);
        }

    }
}
